package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.common.exception.CustException;
import com.heima.feign.ArticleFeignClient;
import com.heima.feign.WemediaFeignClient;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {

        //1.参数的检查
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        dto.checkParam();
        Page<ApUserRealname> apUserRealnamePage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.lambdaQuery();
        //根据前端发来的参数，去查询数据库，分页
            if (dto.getStatus()!=null){
                wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
            }

        IPage<ApUserRealname> page = this.page(apUserRealnamePage, wrapper);
        //响应的结果
        ResponseResult<ApUserRealname> responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),page.getTotal(),page.getRecords());
        return responseResult;
    }

    @Autowired
    private ApUserMapper apUserMapper;
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {

       //1.参数的判断
        Integer id = dto.getId();
        if (id==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.lambdaQuery();
        //.查询realName中是否存在这个用户
        wrapper.eq(ApUserRealname::getId,dto.getId())
                .eq(ApUserRealname::getStatus,1);
        //
        ApUserRealname apUserRealname = this.getOne(wrapper);
        if (apUserRealname==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"AprealNname用户不存在");
        }
        //查询ApUser中是否存在用户
        LambdaQueryWrapper<ApUser> query = Wrappers.lambdaQuery();
         query.eq(ApUser::getId, dto.getId());
        ApUser apUser = apUserMapper.selectOne(query);
        if (apUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"ApUser用户不存在");
        }

        //更新认证用户的状态
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
       if (StringUtils.isNotBlank(dto.getMsg())){
           apUserRealname.setReason(dto.getMsg());
       }
       this.updateById(apUserRealname);
       if ( AdminConstants.PASS_AUTH.equals(status)){
         WmUser wmUser =creatWmUser(dto,apUser);
        createAuthor(wmUser);
       }
        //更新用户信息
        apUser.setFlag((short) 1);
       apUserMapper.updateById(apUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    ArticleFeignClient articleFeign;
    private void createAuthor(WmUser wmUser) {
        //1 检查是否成功调用
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.findByUserId(wmUser.getApUserId());
        if(apAuthorResult.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,apAuthorResult.getErrorMessage());
        }
        //2. 检查作者信息是否已经存在
        ApAuthor apAuthor = apAuthorResult.getData();
        if (apAuthor != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已存在");
        }
        //3. 添加作者信息
        apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2); // 自媒体人类型
        apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
        apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
        ResponseResult result = articleFeign.save(apAuthor);
        //4. 结果失败，抛出异常
        if (result.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }

    }

    @Autowired
    WemediaFeignClient wemediaFeign;
    private WmUser creatWmUser(AuthDTO dto, ApUser apUser) {
        //1 查询自媒体账号是否存在（APP端用户密码和自媒体密码一致）
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());
        if(wmUserResult.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,wmUserResult.getErrorMessage());
        }
        WmUser wmUser =wmUserResult.getData();
        if (wmUser != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"自媒体用户信息已存在");
        }
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());

        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if(saveResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,saveResult.getErrorMessage());
        }
        return saveResult.getData();
    }
}
